package com.three.digit.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

import com.three.digit.ResourcesHanlder;
import com.three.digit.model.Point;

public class SynUpdate implements ResourcesHanlder
{

    private static final Pattern pattern = Pattern.compile ("<li class=\"blue\">(\\d){1}</li>\\s*<li class=\"blue\">(\\d){1}</li>\\s*<li class=\"blue\">(\\d){1}</li>");
    private static final String urlString = "http://kaijiang.zhcw.com/zhcw/inc/3d/3d_index.jsp";

    public void autoSyn ()
    {
        String filePath = ClassLoader.getSystemResource ("").getFile ();
        Utils.writeToFile (HIS_LIST, filePath + "BackUpSanDHistory.txt");

        System.out.println ("--The latest is: " + HIS_LIST.get (HIS_LIST.size () - 1));

        String lastId = HIS_LIST.get (HIS_LIST.size () - 1).getId () + "";

        List <Point> current = autoSyn (lastId);

        for (int i = current.size () - 2; i >= 0; i--)
        {
            HIS_LIST.add (current.get (i));
        }

        Utils.writeToFile (HIS_LIST, filePath + "SanDHistory.txt");
    }

    public List <Point> autoSyn (String breakID)
    {
        List <Point> points = new ArrayList <Point> ();

        Calendar calendar = Calendar.getInstance ();

        for (String id = ""; !breakID.equals (id); calendar.add (Calendar.DAY_OF_YEAR, -1))
        {

            int year = calendar.get (Calendar.YEAR);
            int dayOfYear = calendar.get (Calendar.DAY_OF_YEAR);
            id = year + StringUtils.leftPad (dayOfYear + "", 3, "0");

            try
            {
                String value = parseString (getStr (id));

                points.add (new Point (id, String.valueOf (value.charAt (0)), String.valueOf (value.charAt (1)),
                                       String.valueOf (value.charAt (2))));
            }
            catch (Exception e)
            {
                System.out.println ("ID:='" + id + "',Internal Server Error");
            }
        }

        return points;
    }

    private static String parseString (String str)
    {
        StringBuffer sb = new StringBuffer ();
        Matcher matcher = pattern.matcher (str);

        while (matcher.find () && matcher.groupCount () > 0)
        {
            for (int i = 1, ii = matcher.groupCount (); i <= ii; i++)
            {
                sb.append (matcher.group (i));
            }
        }
        return sb.toString ();
    }

    private String getStr (String id)
    {

        String rtn = "";
        HttpURLConnection urlconn = null;
        InputStream is = null;
        try
        {
            URL url = new URL (urlString);

            urlconn = (HttpURLConnection) url.openConnection ();

            urlconn.setDoOutput (true);
            urlconn.setRequestMethod ("POST");

            StringBuffer param = new StringBuffer ();
            param.append ("issue=" + id);

            OutputStream os = urlconn.getOutputStream ();
            os.write (param.toString ().getBytes ());
            os.close ();

            is = urlconn.getInputStream ();

            rtn = readFromStream (is);

        }
        catch (Exception e)
        {
            try
            {
                rtn = urlconn.getResponseMessage ();
            }
            catch (Exception e2)
            {
                // TODO: handle exception
            }
            // System.out.println("Internal Server Error".equals(el.getMessage()));
            throw new RuntimeException (rtn);
        }
        finally
        {
            urlconn.disconnect ();
        }

        return rtn;
    }

    private String readFromStream (InputStream inputStream)
    {
        StringBuffer sb = new StringBuffer ();

        BufferedReader br = null;
        try
        {
            br = new BufferedReader (new InputStreamReader (inputStream, "UTF-8"));

            String str;
            while ((str = br.readLine ()) != null)
            {
                sb.append (str);
            }

        }
        catch (Exception e)
        {
            e.printStackTrace ();
        }
        finally
        {
            try
            {
                inputStream.close ();
                br.close ();
            }
            catch (IOException e)
            {
                e.printStackTrace ();
            }
        }
        return sb.toString ();
    }

}
